package cn.jia.hrm.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static cn.jia.hrm.common.MQConstants.*;  //hrm-basic-common
/**
 * 消息队列配置
 */
@Configuration
public class MQConfig {



    //创建交换机
    @Bean
    public Exchange topicExchange(){
        return ExchangeBuilder.topicExchange(NAME_EXCHANGE_HRM_TOPIC).build();
    }
    
    //短信队列
    @Bean
    public Queue smsQueue(){

        return new Queue(NAME_QUEUE_HRM_SMS);
    }
    //邮件队列
    @Bean
    public Queue emailQueue()
    {
        return new Queue(NAME_QUEUE_HRM_EMAIL);
    }
    //站内信队列
    @Bean
    public Queue stationMsgQueue(){
        return new Queue(NAME_QUEUE_HRM_STATION_MSG);
    }

    //绑定短信队列
    @Bean
    public Binding bindSmsQueue(){
        return BindingBuilder
                .bind(smsQueue())  //绑定队列
                .to(topicExchange()) //到哪个交换机
                .with("#.sms")  //用什么routingkey
                .noargs();
    }
    //绑定邮件队列
    @Bean
    public Binding bindEmailQueue(){
        return BindingBuilder
                .bind(emailQueue())  //绑定队列
                .to(topicExchange()) //到哪个交换机
                .with("#.email")  //用什么routingkey
                .noargs();
    }
    //绑定站内信队列
    @Bean
    public Binding bindStationMsgQueue(){
        return BindingBuilder
                .bind(stationMsgQueue())  //绑定队列
                .to(topicExchange()) //到哪个交换机
                .with("#.smsg")  //用什么routingkey
                .noargs();  //需要需要参数
    }


    //自定义RabbitTemplate
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //如果消息发送到MQ失败，把消息返回回来
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }

}
